package com.a100.equipment.service.impl;

import com.a100.equipment.entity.EquArchives;
import com.a100.equipment.entity.EquCategory;
import com.a100.equipment.entity.po.PageEquCategoryPo;
import com.a100.equipment.entity.po.PageEquCategoryResponsePo;
import com.a100.equipment.entity.vo.*;
import com.a100.equipment.listener.ArchivesExcelListener;
import com.a100.equipment.mapper.EquArchivesMapper;
import com.a100.equipment.service.EquArchivesService;
import com.a100.equipment.utils.ConstantPropertiesUtils;
import com.a100.utils.exceptionhandler.GuliException;
import com.a100.utils.utils.ResultCode;
import com.alibaba.excel.EasyExcel;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 设备档案 服务实现类
 * </p>
 *
 * @author index
 * @since 2021-12-02
 */
@Service
public class EquArchivesServiceImpl extends ServiceImpl<EquArchivesMapper, EquArchives> implements EquArchivesService {
    @Autowired
    private EquArchivesMapper equArchivesMapper;
    @Value("${excel.storage.address}")
    private  String EXCELADDRESS;
    //新增设备
    @Override
    public boolean saveEquCategoryByVo(CreateEquArchivesVo createEquArchivesVo) {
        if(!StringUtils.isEmpty(createEquArchivesVo)){//传入参数vo不为空
            if(StringUtils.isEmpty(createEquArchivesVo.getAname())){
                //传入名称为空
                return false;
            }else {
                //传入名称不为空
                EquArchives equArchives = new EquArchives();
                //封装数据
                BeanUtils.copyProperties(createEquArchivesVo,equArchives);
                if(StringUtils.isEmpty(createEquArchivesVo.getNumber())){
                    //编号不为空
                    equArchives.setNumber("1024");
                }
                //调用数据库插入
                return this.save(equArchives);
            }
        }
        return false;
    }
    //更新设备
    @Override
    public boolean updateEquCategoryByVo(UpdateEquArchivesVo updateEquArchivesVo) {
        //传入参数vo不为空
        if(!StringUtils.isEmpty(updateEquArchivesVo)){
            if(StringUtils.isEmpty(updateEquArchivesVo.getId())){
                //id为空，直接返回false
                return false;
            }
            //根基id查询数据
            EquArchives equArchives = this.getById(updateEquArchivesVo.getId());
            if(StringUtils.isEmpty(equArchives)){
                //查无数据
                return false;
            }
            //填装修改的数据
            if(!StringUtils.isEmpty(updateEquArchivesVo.getAname())){
                //修改名称
                equArchives.setAname(updateEquArchivesVo.getAname());
            }
            if(!StringUtils.isEmpty(updateEquArchivesVo.getCategoryId())){
                //修改类型
                equArchives.setCategoryId(updateEquArchivesVo.getCategoryId());
            }
            if(!StringUtils.isEmpty(updateEquArchivesVo.getNumber())){
                //修改排序
                equArchives.setNumber(updateEquArchivesVo.getNumber());
            }
            if(!StringUtils.isEmpty(updateEquArchivesVo.getState())){
                //修改状态
                equArchives.setState(updateEquArchivesVo.getState());
            }
            if(!StringUtils.isEmpty(updateEquArchivesVo.getDepartment())){
                //修改部门
                equArchives.setDepartment(updateEquArchivesVo.getDepartment());
            }
            if(!StringUtils.isEmpty(updateEquArchivesVo.getOrganization())){
                //修改组织
                equArchives.setOrganization(updateEquArchivesVo.getOrganization());
            }
            if(!StringUtils.isEmpty(updateEquArchivesVo.getPersonnel())){
                //修改人员
                equArchives.setPersonnel(updateEquArchivesVo.getPersonnel());
            }
            if(!StringUtils.isEmpty(updateEquArchivesVo.getFinancialRegistration())){
                //修改入账状态
                equArchives.setFinancialRegistration(updateEquArchivesVo.getFinancialRegistration());
            }

            //重新插入数据库
            QueryWrapper<EquArchives> wrapper = new QueryWrapper<EquArchives>();
            wrapper.eq("id",equArchives.getId());
            return this.update(equArchives,wrapper);
        }
        return false;
    }
    //条件分页查询设备
    @Override
    public HashMap<String, Object> listPageByQuery(Integer current, Integer pagesize, PageEquCategoryVo pageEquCategoryVo) {
        //前端传入的条件和分页合并一个类
        PageEquCategoryPo pageEquCategoryPo = new PageEquCategoryPo();
        BeanUtils.copyProperties(pageEquCategoryVo,pageEquCategoryPo);
        pageEquCategoryPo.setCurrent(current);pageEquCategoryPo.setPagesize(pagesize);
        //调用mapper获得返回值
        long total=equArchivesMapper.getEquArchivesTotal(pageEquCategoryPo);
        List<PageEquCategoryResponsePo> records=equArchivesMapper.getEquArchivesRecords(pageEquCategoryPo);
        //组装data
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("total",total);
        hashMap.put("rows",records);
        return hashMap;
    }
    //查询单个设备
    @Override
    public PageEquCategoryResponsePo chooseEquArchivesById(Long equArchivesId) {
        return equArchivesMapper.chooseEquArchivesById(equArchivesId);
    }
    //删除单个设备
    @Override
    public boolean deleteEquArchivesById(Long equArchivesId) {
        //查询数据库有无该数据
        EquArchives archives = this.getById(equArchivesId);
        if(StringUtils.isEmpty(archives)){
            return false;
        }
        //删除数据
        return this.removeById(equArchivesId);
    }
    //调用逻辑层完成启用和禁用设备功能
    @Override
    public boolean updateDisableenabledevice(UpdateDisableOrEnableArcvhives udea) {
        //判断要停用还是启用,接受0和1，其他抛弃
        if(udea.getState()==0||udea.getState()==1){
            return equArchivesMapper.updateDisableenabledevice(udea);
        }
        return false;
    }
    //通过Excel批量添加设备
    @Override
    public boolean saveArchivesByExcel(MultipartFile file, EquArchivesService equArchivesService) {
        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(inputStream, ArchivesExcelWriteVo.class,new ArchivesExcelListener(this)).sheet().doRead();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }
    //通过Excel批量导出设备
    @Override
    public String exportArchivesByExcel(){
        //求出全部设备
        QueryWrapper<EquArchives> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_create");
        List<EquArchives> archivesList = this.list(wrapper);
        //定义
        //String fileName = "D:/tempfile.xlsx";   //window
        String fileName = "/usr/local/excel/temp.xlsx";     //Linux
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        //文件不存在则新建
        EasyExcel.write(fileName, ArchivesExcelReadVo.class).sheet("设备列表").doWrite(archivesList);
        //把文件上传阿里云并返回访问路径
        String ossToAddress = fromOssToAddress(fileName);
        return ossToAddress;
    }
    //把文件上传阿里云并返回访问路径
    public String fromOssToAddress(String fileAddress){
        //文件不存在直接抛出错误
        File file=new File(fileAddress);
        if (!file.exists()){
            return null;
        }

        // 工具类获取值
        String endpoint = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
            //组装流
            FileInputStream stream = new FileInputStream(file);
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取上传文件输入流
            InputStream inputStream = stream;
            //获取文件名称
            String fileName = ".xlsx";

            //1 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            // yuy76t5rew01.jpg
            fileName = uuid+fileName;

            //2 把文件按照日期进行分类
            //获取当前日期
            //   2019/11/12
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            //  2019/11/12/ewtqr313401.jpg
            fileName = datePath+"/"+fileName;

            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName,fileName , inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //  https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
